package com.example.modulemine.view.activity.mine;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.example.baselibs.Constant.BaseConstant;
import com.example.baselibs.base.activity.BaseToolBarActivity;
import com.example.baselibs.entity.Result;
import com.example.baselibs.entity.bean.UpdatedInfo;
import com.example.baselibs.net.RetrofitManager;
import com.example.baselibs.net.service.UserApi;
import com.example.baselibs.public_fun.DownLoadApk;
import com.example.baselibs.public_fun.interfaces.VersionUpdateImpl;
import com.example.baselibs.router.path.ModuleMinePath;
import com.example.baselibs.service.DownLoadService;
import com.example.baselibs.utils.ActivityUtils;
import com.example.modulemine.R;
import com.example.modulemine.R2;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

@Route(path = ModuleMinePath.PATH_CHECK_UPDATE)
public class CheckUpdateActivity extends BaseToolBarActivity implements VersionUpdateImpl{
    @BindView(R2.id.tv_current_version)
    TextView current_version;
    @BindView(R2.id.tv_new_version)
    TextView new_version;

    private UpdatedInfo updatedInfo;
    private String apkName;
    private boolean isUpdate=false;
    @Override
    public String setTitle() {
        return "检查更新";
    }

    @Override
    public int getLayoutRes() {
        return R.layout.activity_check_update;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        current_version.setText("V"+ActivityUtils.getVersion(this));
        updated();
    }

    /**
     * 检查是否有新版本更新
     */
    private void updated() {
        Map<String, String> map = new HashMap<>();
        map.put("O[UPDATE_TIME]", "desc");
        map.put("L[0]", "1");
        map.put("W", "(VERSIONCODE > " + ActivityUtils.getVersionCode(this) + " and ( ISTEST=0 and SOFT_ID=1))");
        RetrofitManager.getInstance().getUserApiService(UserApi.class).install(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<UpdatedInfo>>() {
                    @Override
                    public void accept(Result<UpdatedInfo> updatedInfoResult) throws Exception {
                        if (updatedInfoResult.isStatus()){
                            isUpdate=updatedInfoResult.isStatus();
                            updatedInfo= updatedInfoResult.getData().get(0);
                            new_version.setText("V"+updatedInfo.getVersion());
                        }else {
                            new_version.setText("暂无更新");
                        }
                    }
                });
    }

    @OnClick(R2.id.tv_new_version)
    public void onUpdateClick(View view){//下载更新
        if (isUpdate){
            apkName=updatedInfo.getDownload().substring(updatedInfo.getDownload().lastIndexOf("/"));
            DownLoadApk.checkNetworkState(this,updatedInfo.getDownload(),1, BaseConstant.APK_PATH_DIR+apkName);
        }else {
            ActivityUtils.showToast(this,"已是最新版本！");
        }

    }

    /**
     * 检查网络是否链接，链接类型
     */
    public void checkNetworkState(){
        if(NetworkUtils.isConnected()&&NetworkUtils.isAvailable()){
            if (NetworkUtils.isMobileData()){
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("下载提示");
                builder.setMessage("您正在使用流量下载应用，是否继续？");
                builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("继续", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //继续下载
                    }
                });
                builder.create().show();
            }
            if (NetworkUtils.isWifiConnected()&&NetworkUtils.isWifiAvailable()){
                //下载
            }

        }else {
            ActivityUtils.showToast(this,"网络不可用，请设置网络！");
            NetworkUtils.openWirelessSettings();
        }
    }
    Intent intent;
    @Override
    public void bindService(String apkUrl, int i, String apkPath) {
        Intent intent = new Intent(this, DownLoadService.class);
        intent.putExtra(DownLoadService.BUNDLE_KEY_DOWNLOAD_URL, apkUrl);
        intent.putExtra(DownLoadService.BUNDLE_KEY_APK_PATH, apkPath);
        intent.putExtra("index", i);
        startService(intent);
        Log.i("bbq","启动服务");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }



}
